import './style.css'
import { Launcher } from 'live-cat'
import type { BaseOptionsType, ExtendOptionType } from 'live-cat/types/client/interface'
import { Message, RECV, SEND } from './interface';
import { Connection } from 'ray-streaming/types';

let launch: Launcher;
let connection: Connection;

// 基础选项
const baseOptions: BaseOptionsType = {
  address: "https://app.3dcat.live",
  appKey: "l7JOP0OWDdvakZb5",
  startType: 1
};

// 扩展选项
const extendOptions: ExtendOptionType = {
  loadingImage: "loading.png",
  toolBarLogoImage: "logo.png",
  // 虚拟控件挂载回调(返回挂载父节点)
  onMount: () => {
  },
  // 开始播放
  onPlay() {
    // 主动发送一次浏览器标识
    sendAgent();
  }
}

// 处理方法
const handlerGetAgent = () => {
  sendAgent();
}

// 注册处理方法
const handlerPacket: {
  [key: number]: (msg: Message) => void
} = {
  [RECV.GET_USER_AGENT]: handlerGetAgent
};

// 发送浏览器标识
const sendAgent = () => {
  let msg: Message = {
    code: SEND.SEND_USER_AGENT,
    data: window.navigator.userAgent
  };

  sendMessage(msg);
}

// 发送消息
const sendMessage = (msg: Message) => {
  console.log("发送消息", msg)
  connection && connection.emitUIInteraction(JSON.stringify(msg))
  .then(res => {
    console.log(res);
    
    if (!res) {
      console.log("发送消息失败!");
    }
  })
  .catch(err => {
    console.log("发送消息出现问题!", err);
  })
}

const init = async () => {
  const player = document.querySelector("body");

  if (!player) {
    console.log("读取节点出错!");
    return
  }

  try {
    launch = new Launcher({baseOptions, extendOptions});
    await launch.automata(player);
    connection = launch.getConnection();
    connection.event.interaction.on(msg => {
      let json;
      console.log("收到消息:", msg);
      try {
        json = JSON.parse(msg as string) as Message;
      } catch (error) {
        console.log("解析json字符串失败", error);
        return
      }
      handlerPacket[json.code] && handlerPacket[json.code](json);
    });
  } catch (error) {
    alert("初始化失败，请刷新浏览器重试!");
    console.error(error);
  }
};

window.addEventListener("DOMContentLoaded", () => {
  if (
    navigator.userAgent.includes("miniProgram") ||
    navigator.userAgent.includes("MicroMessenger")
  ) {
    //微信浏览器/微信小程序环境
    document.addEventListener("WeixinJSBridgeReady", init, false);
  } else {
    init();
  }
});